package backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * 17.电话号码的字母组合
 * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
 * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 */
public class letterCombinations {
    /**
     * 该题有难度，与之前的不同，需要着重复习
     * hot100一刷
     */
    List<String> list = new ArrayList<>();

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return list;
        }
        //初始对应所有的数字，为了直接对应2-9，新增了两个无效的字符串""
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        //迭代处理
        back(digits, numString, 0);
        return list;
    }

    StringBuilder temp = new StringBuilder();

    public void back(String digits, String[] numString, int num) {
        if (num == digits.length()) {
            list.add(temp.toString());
            return;
        }
        String str = numString[digits.charAt(num) - '0'];
        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            //递归，处理下一层
            back(digits, numString, num + 1);
            //剔除末尾的继续尝试
            temp.deleteCharAt(temp.length() - 1);
        }
    }


}

class ution {
    static String[] arry = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    static List<String> res = new ArrayList<>();

    public static List<String> letterCombinations(String digits) {
        if (digits.length() == 0) {
            return res;
        }
        backtracking(digits, 0, new StringBuffer());
        return res;
    }

    public static void backtracking(String digits, int start, StringBuffer s) {
        if (start > digits.length()) {
            return;
        }
        if (s.length() == digits.length()) {
            res.add(s.toString());
            return;
        }
        char[] arr = arry[digits.charAt(start)-'0'].toCharArray();
        for (int i = 0; i < arr.length; i++) {

            s.append(arr[i]);
            backtracking(digits, start + 1, s);
            s.deleteCharAt(s.length() - 1);
        }
    }
}

/**
 * hot100二刷
 */
class SS {
    List<String> res = new ArrayList<>();
    StringBuffer sb = new StringBuffer();
    String[] arr = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0)
            return res;
        backtracking(digits, 0);
        return res;
    }

    public void backtracking(String digits, int start) {
        if (start == digits.length()) {
            res.add(sb.toString());
            return;
        }
        char ch = digits.charAt(start);
        ch -= '0';
        for (char c : arr[ch].toCharArray()) {
            sb.append(c);
            backtracking(digits, start + 1);
            sb.deleteCharAt(sb.length() - 1);
        }

    }
}
